package com.study.leetcode;

import java.util.ArrayList;
import java.util.List;

//https://leetcode-cn.com/problems/generate-parentheses/
public class GenerateParentheses {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        if (n == 0) {
            return res;
        }
        //使用dfs
        dfs("", n, n, res);
        return res;
    }

    private void dfs(String curStr, int left, int right, List<String> res) {
        //如果全部括号都正确就添加
        if (left == 0 && right == 0) {
            res.add(curStr);
            return;
        }
        //因为这里必须先有左括号所以左括号剩余个数不可能不右括号多
        //剪枝
        if (left > right) {
            return;
        }

        //先左递归
        if (left > 0) {
            dfs(curStr + "(", left - 1, right, res);
        }
        //右递归
        if (right > 0) {
            dfs(curStr + ")", left, right - 1, res);
        }
    }
}
